package com.juqimiao.raccoon.commodity.command;

import com.juqimiao.linn.command.CommandExecutor;
import com.juqimiao.linn.command.CommandExecutorI;
import com.juqimiao.linn.exception.BasicError;
import com.juqimiao.linn.exception.BusinessException;
import com.juqimiao.linn.extension.ExtensionExecutor;
import com.juqimiao.linn.transfer.Response;
import com.juqimiao.linn.transfer.query.builders.ResponseBuilder;
import com.juqimiao.raccoon.commodity.appobj.CategoryGroupPublishAO;
import com.juqimiao.raccoon.commodity.domain.CategoryGroupFactory;
import com.juqimiao.raccoon.commodity.domain.category.CategoryGroup;
import com.juqimiao.raccoon.commodity.dto.SwitchCategoryGroupPublishCmd;
import com.juqimiao.raccoon.commodity.extension.CategoryGroupValidExtPt;
import com.juqimiao.raccoon.commodity.repository.CategoryGroupRepository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@CommandExecutor
public class SwitchCategoryGroupPublishExt implements CommandExecutorI<Response, SwitchCategoryGroupPublishCmd> {

    private ExtensionExecutor extensionExecutor;

    private CategoryGroupFactory factory;

    private CategoryGroupRepository repository;

    @Autowired
    public SwitchCategoryGroupPublishExt(ExtensionExecutor extensionExecutor,
                                         CategoryGroupFactory factory,
                                         CategoryGroupRepository repository) {
        this.extensionExecutor = extensionExecutor;
        this.factory = factory;
        this.repository = repository;
    }

    @Override
    public Response execute(SwitchCategoryGroupPublishCmd cmd) {
        Response response = null;
        List<CategoryGroup> groupList = new ArrayList<>();
        /* Data Validation */
        extensionExecutor.executeVoid(CategoryGroupValidExtPt.class,
                extension -> extension.validate(cmd));
        for (CategoryGroupPublishAO pubAO : cmd.getCategoryGroupAOList()) {
            /* Restore CategoryGroup */
            CategoryGroup categoryGroup = factory.create(repository, pubAO.getId());
            if (categoryGroup == null) {
                throw new BusinessException(String.format("CategoryGroup %s does not exist.", pubAO.getId()));
            }

            categoryGroup.setPublish(pubAO.isPublish());
            groupList.add(categoryGroup);
        }
        /* Persis the data into database */
        int count = repository.publish(groupList);
        if (count != 1) {
            response = ResponseBuilder.builder().failure(
                    BasicError.SYSTEM_ERROR.getErrorCode(), "CategoryGroup batchUpdate failed.");
        } else {
            response = ResponseBuilder.builder().success("CategoryGroup batchUpdate successfully.").build();
        }
        return response;
    }
}
